package com.zy.datareceiver.core.utils;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zy.datareceiver.core.example.ParameterException;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*;

/**
 * 参数校验
 * */
public class BeanValidator {
    private static final Logger log = LoggerFactory.getLogger(BeanValidator.class);

    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    /**
     * @desc 对参数进行校验
     * @author ccp
     * @param  t 需要校验的参数类型
     * @param  clazzes 检验的参数类型
     * @return map 以错误字段为key，错误信息为value的map
     * */
    public static <T> Map<String, String>  validata(T t, Class... clazzes){
        Validator validator =  validatorFactory.getValidator();
        Set validatorResult = validator.validate(t,clazzes);
        if (validatorResult.isEmpty()){
            return Collections.emptyMap();
        }else {
            LinkedHashMap errors = Maps.newLinkedHashMap();
            Iterator iterator = validatorResult.iterator();
            while (iterator.hasNext()){
                ConstraintViolation violation = (ConstraintViolation) iterator.next();
                errors.put(violation.getPropertyPath().toString(),violation.getMessage());
            }
            return errors;
        }
    }

    public static <T> Map<String, String> validataList(Collection<?> collection){
        Preconditions.checkNotNull(collection);
        Iterator iterator = collection.iterator();
        Map errors;
        do {
            if (!iterator.hasNext()){
                return Collections.emptyMap();
            }
            Object object = iterator.next();
            errors = validata(object, new Class[0]);
        }while(errors.isEmpty());
        return errors;
    }

    public static Map<String, String> validateObject(Object first, Object... objects) {
        if (objects != null && objects.length > 0) {
            return validataList(Lists.asList(first, objects));
        } else {
            return validata(first, new Class[0]);
        }
    }

    public static void checkParam(Object object){
        Map<String, String> map = validateObject(object);
        if (MapUtils.isNotEmpty(map)){
            throw ParameterException._404(map.toString());
        }
    }
}
